<template>
  <div class="form-select product-type-quality-startTime">
    <!-- 产品类型质保起算时间 -->
    <el-select
      :id="`form_${field.fieldName}`"
      v-model="newValue"
      :style="{ width: '100%' }"
      @change="update"
      :popper-append-to-body="false"
      :placeholder="placeholder"
      :clearable="clearable"
    >
      <el-option
        v-for="(item, index) in productOption"
        :key="`${item.value}_${index}`"
        :label="item.text"
        :value="item.value"
      ></el-option>
    </el-select>
  </div>
</template>

<script>
import FormMixin from '@src/component/form/mixin/form';
import { getProductFields } from '@src/api/ProductApi';
import { useFormMultiLanguage } from '@hooks/useFormMultiLanguage';
import i18n from '@src/locales'

export default {
  name: 'product-type-quality-startTime',
  mixins: [FormMixin],
  props: {
    value: {
      type: Object | String,
      default: () => ({}),
    },
    clearable: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      newValue: this.value,
      productOption: [],
      ...useFormMultiLanguage()
    };
  },
  watch: {
    value(newValue) {
      this.newValue = newValue;
    },
  },
  mounted() {
    if (this.field.setting.dataType == 1) {
      // 关联产品日期
      this.getProductFields();
    } else {
      // 自定义日期
      this.getSelectList();
    }
  },
  methods: {
    // 自定义下拉框数据处理
    getSelectList() {
      let setting = this.field?.setting || {};
      let dataSource = (this.internationalGray && setting.dataSourceLanguage?.[i18n.locale]) || setting.dataSource || [];

      this.productOption = dataSource.map(d => {
        if (typeof d === 'string') {
          return {
            text: d,
            value: d,
          };
        }
        return d;
      }).filter(item => item.value !== '');
    },
    // 获取关联产品日期下拉框
    async getProductFields() {
      let res = await getProductFields({ isFromSetting: false });

      if (res.data.length == 0) return;

      let arr = [];
      res.data.forEach(item => {
        if (this.field?.setting?.fieldNames.includes(item.fieldName)) {
          arr.push(item);
        }
      });

      this.productOption = arr.map(item => {
        return {
          text: item.displayName,
          value: item.fieldName,
        };
      });
    },
    update(newValue) {
      let oldValue = null;

      this.$emit('update', { newValue, oldValue, field: this.field });
      this.$emit('input', newValue);
    },
  },
};
</script>
